<?php
	include("includes/connect_db.php");

	// Post Variabel
	$lokasi = $_POST['lokasi'];
	$log = $_POST['log'];
	$pin = $_POST['pin'];
	$user = $_POST['user'];
	$pass = $_POST['pass'];
	$host = $_POST['host'];
	$db = $_POST['db'];
	$gammu = $_POST['gammu'];

	$logFile = $log.".txt";
	$log_dir = $lokasi."\\".$logFile;
	$jumlah = count($gammu);
	echo $jumlah;

	// Pecah Variabel Gammu
	for ($i=0; $i < $jumlah; $i++) { 	
		$port[$i] = $gammu[$i][0];
		$koneksi[$i] = $gammu[$i][1];
		$idAlat[$i] = $gammu[$i][2];
		$idProvider[$i] = $gammu[$i][3];
	}

	// Simpan Ke Database
	$sql_cek = "SELECT * FROM tb_setting_gammu";
	$query_cek = mysql_query($sql_cek);
	$cek = mysql_num_rows($query_cek);

	if ($cek == 0) {
		$sql_simpan = "INSERT INTO tb_setting_gammu (id_Setting_gammu, lokasi, nama_log, pin, user, pass, host, db)
						VALUES (1, '".addslashes($lokasi)."', '$log', '$pin', '$user', '$pass', '$host', '$db')";
	} else {
		$sql_simpan = "UPDATE tb_setting_gammu SET lokasi='".addslashes($lokasi)."', nama_log='$log', pin=$pin, 
						user='$user', pass='$pass', host='$host', db='$db' WHERE id_Setting_gammu='1'";
	}
	$query_simpan = mysql_query($sql_simpan);

	$sql_hapus = "TRUNCATE tb_setting_gammu_detail";
	$query_hapus = mysql_query($sql_hapus);
	for ($i=0; $i < $jumlah; $i++) { 
		$sql_simpan = "INSERT INTO tb_setting_gammu_detail (id_setting_gammu, nama_alat, port, koneksi, id_provider)
						VALUES (1, '$idAlat[$i]', '$port[$i]', '$koneksi[$i]', '$idProvider[$i]')";
		$query_simpan = mysql_query($sql_simpan);
		echo $sql_simpan;
	}

	$gammu_dir = $lokasi."\gammurc2";
	$isi = "";
	for ($i=0; $i < $jumlah; $i++) { 
		if ($i == 0) {
			$head = "[gammu]";
		} else {
			$head = "[gammu".$i."]";
		}

		$isi = 	$isi.$head."\r\n".
				"port = ".$port[$i]."\r\n".
				"connection = ".$koneksi[$i]."\r\n\r\n".
				"[smsd]\r\n".
				"service=sql\r\n".
				"driver=native_mysql\r\n".
				"PIN=".$pin."\r\n".
				"LogFile=".$log_dir."\r\n".
				"user=".$user."\r\n".
				"password=".$pass."\r\n".
				"host=".$host."\r\n".
				"database=".$db."\r\n\r\n";

	}
	$file_gammu = fopen($gammu_dir, "w");
 	fputs($file_gammu, "$isi");
 	fclose($file_gammu);
?>